package cn.s1995.sloth.app.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.s1995.sloth.common.core.util.SpringContextHolder;
import lombok.experimental.UtilityClass;
import org.springframework.core.env.Environment;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * PasswordUtil
 *
 * @author Lex
 * @description
 * @date 2023/12/27 14:21
 */
@UtilityClass
public class PasswordUtil {
    private static final String KEY_ALGORITHM = "AES";
    public static final String DEFAULT_KEY = "pigxpigxpigxpigx";

    public static void main(String[] args) {
        String pwd = "a123123";
        String encode = encode(pwd);
        String decode = decode(encode);
        System.out.println("encode = " + encode);
        System.out.println("decode = " + decode);

        System.out.println(encode(encode));
    }

    /**
     * 密码解密
     * @param presentedPassword 加密密码
     */
    public static String encode(String presentedPassword) {
        String key;
        try {
            // 构建前端对应解密AES 因子
            Environment bean = SpringContextHolder.getBean(Environment.class);
           key = bean.getProperty("gateway.encodeKey", DEFAULT_KEY);
        } catch (Exception e) {
            key = DEFAULT_KEY;
        }
        AES aes = new AES(Mode.CFB, Padding.NoPadding, new SecretKeySpec(key.getBytes(), KEY_ALGORITHM),
                new IvParameterSpec(key.getBytes()));
        return aes.encryptBase64(presentedPassword);
    }


    /**
     * 密码解密
     * @param presentedPassword 加密密码
     */
    public static String decode(String presentedPassword) {
        String key;
        try {
            // 构建前端对应解密AES 因子
            Environment bean = SpringContextHolder.getBean(Environment.class);
            key = bean.getProperty("gateway.encodeKey", DEFAULT_KEY);
        } catch (Exception e) {
            key = DEFAULT_KEY;
        }
        AES aes = new AES(Mode.CFB, Padding.NoPadding, new SecretKeySpec(key.getBytes(), KEY_ALGORITHM),
                new IvParameterSpec(key.getBytes()));
        return aes.decryptStr(presentedPassword);
    }
}
